package cn.tnar.parkservice.service.impl;

import cn.tnar.parkservice.config.Constant;
import cn.tnar.parkservice.config.jwt.JwtUtil;
import cn.tnar.parkservice.exception.CustomException;
import cn.tnar.parkservice.mapper.UserMapper;
import cn.tnar.parkservice.model.dto.MenuDto;
import cn.tnar.parkservice.model.entity.TSysMenu;
import cn.tnar.parkservice.model.entity.User;
import cn.tnar.parkservice.model.response.TSysMenuDto;
import cn.tnar.parkservice.service.ITSysMenuService;
import cn.tnar.parkservice.service.IUserService;
import cn.tnar.parkservice.service.KesbApiService;
import cn.tnar.parkservice.util.common.ResultCode;
import cn.tnar.parkservice.util.common.ResultJson;
import cn.tnar.pms.kesb.KesbException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author qu
 */
@Service("UserServiceImpl")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private KesbApiService kesbApiService;

    @Value("${api.path}")
    public static final String C_GET_CUSTOMER_INFO = "http://park_api/kesb/api/";
    public static final String C_TREE_INFO = "http://park_api/kesb/api/ent/tree/";

    @Autowired
    private ITSysMenuService sysMenuService;

    private ResultJson resultJson = new ResultJson();

    @Override
    public ResultJson userLogin(User user) {

        Map<String, Object> param = new HashMap<>();
        param.put("g_custsession", "");
        param.put("g_funcid", Constant.C_LOGIN_INFO);
        param.put("g_custid", "0");
        param.put("login_from_type", "51");
        param.put("usr_code", user.getAccount());
        param.put("trade_pwd", user.getPassword());

        //  调用登录，验证用户名和密码
        Map<String, String> map = null;
        try {
            map = kesbApiService.queryKesbApi(Constant.C_LOGIN_INFO, param);
            log.info("登录返回信息：========"+map);
        } catch (KesbException e) {
            return resultJson.setCode(400).setMsg(e.getMessage()).setData(map);
        }

        String jwt = JwtUtil.creatToken(user.getAccount());
        map.put("token", jwt);
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(map);

    }

    public List<Map<String, String>> selectParkInfo(String json) {

        Map mapObj = JSON.parseObject(json, HashMap.class);
        Map<String, Object> param = new HashMap<>();
        param.put("g_custsession", mapObj.get("session"));
        param.put("g_funcid", "82202082");
        param.put("g_custid", mapObj.get("custid"));
        param.put("cust_parent_id", mapObj.get("cust_parent_id"));
        param.put("isself", "1");
        param.put("park", "1");
        param.put("maxid", "0");
        param.put("maxcount", "10000");
        //  获取停车场和运营商信息
        return kesbApiService.queryKesbApiList("82202082", param);

    }

    public List<Map<String, String>> selectOperator(String json) {
        Map mapObj = JSON.parseObject(json, HashMap.class);
        Map<String, Object> param = new HashMap<>();
        param.put("g_custsession", mapObj.get("session"));
        param.put("g_funcid", "82101813");
        param.put("g_custid", mapObj.get("custid"));
        param.put("usr_code", mapObj.get("account"));
        //  获取企业操作员信息
        return kesbApiService.queryKesbApiList(Constant.C_OPERATOR_INFO, param);

    }

    public List<MenuDto> selectMenu(Map mapObj) {
//        Map<String,Object> param = new HashMap<>();
//        param.put("g_custsession",mapObj.get("session"));
//        param.put("g_funcid","81103110");
//        param.put("g_custid",mapObj.get("custid"));
//        param.put("parent_menu_id","1");
//        param.put("include_root","0");
//        param.put("menuFlag","1,2");
//        param.put("role_id",mapObj.get("role_id"));
//        param.put("platform_type",2);
//        //  取系统菜单
//        return kesbApiService.queryKesbApiList(Constant.C_MENU_INFO, param);

        return sysMenuService.selectMenu(mapObj.get("custid").toString());
    }

    @Override
    public ResultJson informationByAll(String json) {

        Map<String, Object> map = new HashMap<>();
        //  获取停车场和运营商信息
        try {
            List<Map<String, String>> filterPark = new ArrayList<>();
            List<Map<String, String>> parkInfo = this.selectParkInfo(json);
            for (Map<String, String> item : parkInfo) {
                if (item.get("type").equals("4")) {
                    filterPark.add(item);
                }
            }
            map.put("parkInfo", filterPark);
        } catch (Exception e) {
            throw new CustomException("获取停车场和运营商信息失败");
        }

        //  获取企业操作员信息
        String role_id = null;
        try {
            List<Map<String, String>> operatorInfo = this.selectOperator(json);
            role_id = operatorInfo.get(0).get("role_id");
            map.put("operatorInfo", operatorInfo);
        } catch (Exception e) {
            throw new CustomException("获取企业操作员信息失败");
        }
        //  取系统菜单
        try {
            Map mapObj = JSON.parseObject(json, HashMap.class);
            mapObj.put("role_id", role_id);
            List<MenuDto> menuInfo = this.selectMenu(mapObj);
            map.put("menuInfo", menuInfo);
        } catch (Exception e) {
            throw new CustomException("取系统菜单失败");
        }

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(map);
    }

    @Override
    public ResultJson informationTree() {
        TSysMenu tSysMenu = sysMenuService.selectYunRoot();
        TSysMenuDto tSysMenuDto = new TSysMenuDto();
        BeanUtils.copyProperties(tSysMenu, tSysMenuDto);
        if (tSysMenuDto != null) {
            tSysMenuDto = getRoleTree(tSysMenuDto);
            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(tSysMenuDto);
        }
        return null;
    }


    private TSysMenuDto getRoleTree(TSysMenuDto tSysMenuDto) {
        Long id = tSysMenuDto.getId();
//        QueryWrapper<TSysMenu> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("parent_menu_id", id);
        List<TSysMenuDto> list = sysMenuService.selectSubByParentId(id).parallelStream().filter(Objects::nonNull)
                .map(x -> {
                    TSysMenuDto dto = new TSysMenuDto();
                    BeanUtils.copyProperties(x, dto);
                    return dto;
                }).collect(Collectors.toList());
        tSysMenuDto.getChilds().addAll(list);
        for (TSysMenuDto dto : list) {
            getRoleTree(dto);
        }
        return tSysMenuDto;
    }
}
